import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// Future对象表示异步操作的结果，我们通常通过then（）来处理返回的结果
// async用于标明函数是一个异步函数，其返回值类型是Future类型
// await用来等待耗时操作的返回结果，这个操作会阻塞到后面的代码

class HttpUtil {
  factory HttpUtil() => _httpInstance();
  static HttpUtil? _instance;
  late Dio _dio;

  HttpUtil._internal() {
    var options = BaseOptions(
        baseUrl: 'http://testhxys.hengxunyun.com',
        connectTimeout: 5000,
        receiveTimeout: 3000,
        contentType: Headers.formUrlEncodedContentType);
        //请求的Content-Type，默认值是[ContentType.json]. 也可以用ContentType.parse("application/x-www-form-urlencoded")
        //contentType: ContentType.json,
        //表示期望以那种格式(方式)接受响应数据。接受三种类型 `json`, `stream`, `plain`, `bytes`. 默认值是`json`,
        //responseType: ResponseType.plain,
    _dio = new Dio(options);
  }

  static HttpUtil _httpInstance() {
    if (_instance == null) {
      _instance = new HttpUtil._internal();
    }
    return _instance!;
  }

  ///Get请求
  void getHttp<T>(
    String url, {
    parameters,
    required Function(T) onSuccess,
    Function(String error)? onError,
  }) async {
    ///定义请求参数
    parameters = parameters ?? {};
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      response = await _dio.get(url, queryParameters: parameters);
      var responseData = response.data;
      if (responseData['code'] == '200') {
        if (onSuccess != null) {
          onSuccess(responseData);
        }
      } else {
        throw Exception('erroMsg:${responseData['erroMsg']}');
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
      onError!(e.toString());
    }
  }

  ///Post请求
  void postHttp<T>(
    String url, {
    parameters,
    required Function(T) onSuccess,
  }) async {
    ///定义请求参数
    parameters = parameters ?? {};
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      response = await _dio.post(url, queryParameters: parameters);
      var responseData = response.data;
      if (responseData['code'] == '200') {
        if (onSuccess != null) {
          onSuccess(responseData);
        }
      } else {
        EasyLoading.dismiss();
        EasyLoading.showToast("${responseData['msg']}");
        // throw ("${responseData['msg']}");
      }
    } on DioError catch (e) {
      EasyLoading.dismiss();
      formatError(e);
    }
  }
}

// error统一处理
void formatError(DioError e) {
  if (e.type == DioErrorType.connectTimeout) {
    // It occurs when url is opened timeout.

    EasyLoading.showToast("连接超时");
  } else if (e.type == DioErrorType.sendTimeout) {
    // It occurs when url is sent timeout.

    EasyLoading.showToast("请求超时");
  } else if (e.type == DioErrorType.receiveTimeout) {
    //It occurs when receiving timeout

    EasyLoading.showToast("响应超时");
  } else if (e.type == DioErrorType.response) {
    // When the server response, but with a incorrect status, such as 404, 503...

    EasyLoading.showToast("服务器异常");
  } else if (e.type == DioErrorType.cancel) {
    // When the request is cancelled, dio will throw a error with this type.

    EasyLoading.showToast("请求取消");
  } else {
    //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
    EasyLoading.showToast("未知错误");
  }
}

// 手机验证
class Yz {
  bool isPhone(String phone) {
    RegExp reg = RegExp(r"1[3456789]\d{9}$");
    if (!reg.hasMatch(phone)) {
      EasyLoading.showToast('请输入有效的手机号码');
      return false;
    } else
      return true;
  }
}
